#include "oaction.h"

#include <QEvent>

OAction::OAction(const QIcon& icon, const QString& text,  const QKeySequence& shortcut,
				 const OTask* start, const OTaskRoutineMap& routine,
				 const QString& toolBarName, const QString& menuName, 
				 const QStringList& supportedWidgetNames, QObject *parent)
	: QAction(icon, text, parent), m_startTask(start), m_curTask(0), m_routine(routine),
	m_menuName(menuName), m_toolBarName(toolBarName), m_supportedWidgetNames(supportedWidgetNames)
{
	setShortcut(shortcut);
	connect(this, SIGNAL(triggered()), this, SLOT(startRoutine()));
}

OAction::OAction(const ODescriptor<OAction>& d, QObject* parent = 0)
	: QAction(d.icon, d.text, parent), m_startTask(d.start), m_curTask(0), m_routine(d.routine),
	m_menuName(d.menuName), m_toolBarName(d.toolBarName), m_supportedWidgetNames(d.supportedWidgetNames)
{
	setShortcut(d.shortcut);
	connect(this, SIGNAL(triggered()), this, SLOT(startRoutine()));
}

OAction::~OAction()
{

}

//void OAction::installBehind(const OTask* pre, int ret, const OTask* t)
//{
//	m_routine[QPair<int, int>(pre, ret)] = t;
//}

bool OAction::onCurrentWindowChanged(const OWindow* w)
{
	reset();
	QWidget* widget = 0;
	if(w && widget = w->widget() 
		&& m_supportedWidgetNames.contains(widget->objectName())){
			setEnabled(true);
			return true;
	}else{
		setEnabled(false);
		return false;
	}
}

void OAction::startRoutine()
{
	m_curTask = m_startTask;
	m_curTask->start();
}

void OAction::reset()
{
	m_startTask = start;
	m_curTask = 0;
}

void OAction::translate(int ret)
{
	m_curTask = m_routine.value(QPair<OTask*, int>(m_curTask, ret), 0);
	if(m_curTask)
		m_curTask->start();
	else
		emit finished();
}
